﻿namespace Summoner
{
    using Newtonsoft.Json;
    using System.IO;
    using System.Text.RegularExpressions;

    public class JsonSerializer
    {
        public static string PackJson(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public static T UnpackJson<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(StripComments(json));
        }

        public static void PackJsonToFile(string path, object obj, string name)
        {
            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }
            string filePath = path + "/" + name + ".json";
            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                StreamWriter writer = new StreamWriter(fs);
                writer.Write(PackJson(obj));
                writer.Close();
                fs.Close();
            }
        }

        public static T UnpackJsonFromFile<T>(string filePath)
        {
            T info = default(T);
            using (StreamReader sr = new StreamReader(File.Open(filePath, FileMode.Open)))
            {
                info = UnpackJson<T>(StripComments(sr.ReadToEnd()));
            }
            return info;
        }

        public static T UnpackJsonFromFile<T>(string path, string name)
        {
            return UnpackJsonFromFile<T>(path + "/" + name + ".json");
        }

        /// <summary>
        /// Strip comments
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private static string StripComments(string code)
        {
            var re = @"(@(?:""[^""]*"")+|""(?:[^""\n\\]+|\\.)*""|'(?:[^'\n\\]+|\\.)*')|//.*|/\*(?s:.*?)\*/";
            return Regex.Replace(code, re, "$1");
        }
    }
}